package com.atguigu.gmall.list.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.list.dao.GoodsDao;
import com.atguigu.gmall.list.service.ListService;
import com.atguigu.gmall.model.list.*;
import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.model.product.BaseTrademark;
import com.atguigu.gmall.model.product.SkuAttrValue;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ListServiceImpl implements ListService {

    @Autowired
    ProductFeignClient productFeignClient;

    @Autowired
    GoodsDao goodsDao;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RestHighLevelClient restHighLevelClient;

    //上架
    @Override
    public void upperGoods(Long skuId) {

        Goods goods = new Goods();

        //1：根据skuID查询SkuInfo信息
        SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
        goods.setId(skuId);
        goods.setDefaultImg(skuInfo.getSkuDefaultImg());
        goods.setTitle(skuInfo.getSkuName());
        goods.setPrice(skuInfo.getPrice().doubleValue());
        goods.setCreateTime(new Date());
        //2:根据tmId 查询品牌相关数据
        BaseTrademark baseTrademark = productFeignClient.getBaseTrademark(skuInfo.getTmId());
        goods.setTmId(skuInfo.getTmId());
        goods.setTmName(baseTrademark.getTmName());
        goods.setTmLogoUrl(baseTrademark.getLogoUrl());
        //3:根据category3Id查询分类视图
        BaseCategoryView baseCategoryView = productFeignClient.getBaseCategoryView(skuInfo.getCategory3Id());
        goods.setCategory1Id(baseCategoryView.getCategory1Id());
        goods.setCategory2Id(baseCategoryView.getCategory2Id());
        goods.setCategory3Id(baseCategoryView.getCategory3Id());
        goods.setCategory1Name(baseCategoryView.getCategory1Name());
        goods.setCategory2Name(baseCategoryView.getCategory2Name());
        goods.setCategory3Name(baseCategoryView.getCategory3Name());
        //4：根据skuId 查询 sku_attr_value   base_attr_info  base_attr_value
        List<SkuAttrValue> skuAttrValueList = productFeignClient.getSkuAttrValue(skuId);
        List<SearchAttr> searchAttrList  = skuAttrValueList.stream().map(skuAttrValue -> {
            SearchAttr searchAttr = new SearchAttr();
            searchAttr.setAttrId(skuAttrValue.getBaseAttrInfo().getId());
            searchAttr.setAttrName(skuAttrValue.getBaseAttrInfo().getAttrName());
            searchAttr.setAttrValue(skuAttrValue.getBaseAttrValue().getValueName());
            return searchAttr;
        }).collect(Collectors.toList());
        goods.setAttrs(searchAttrList);
        //保存索引库
        goodsDao.save(goods);
    }
    //下架
    @Override
    public void lowerGoods(Long skuId) {
        goodsDao.deleteById(skuId);
    }

    @Override
    public void hotScore(Long skuId) {
        Double hostScore = redisTemplate.opsForZSet().incrementScore("hostScore", skuId, 1);
        if (hostScore%10 == 0){
            //1:查询ES库 此商品的评分
            Optional<Goods> goods1 = goodsDao.findById(skuId);
            Goods goods = goods1.get();
            //2:将此评分加分
            goods.setHotScore(Math.round(hostScore));
            //3:此商品保存回ES库
            goodsDao.save(goods);
        }
    }

    //开始搜索
    @Override
    public SearchResponseVo search(SearchParam searchParam) {
        SearchResponseVo searchResponseVo = null;
        //1:构建搜索请求对象
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        //2:执行搜索
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //3:解析结果对象
            searchResponseVo = parseSearchResponse(searchResponse);
            //当前页
            searchResponseVo.setPageNo(searchParam.getPageNo());
            //每页数
            searchResponseVo.setPageSize(searchParam.getPageSize());
            //总页数 == （总条数 + 每页数 -1)/每页数
            searchResponseVo.setTotalPages((searchResponseVo.getTotal()+searchParam.getPageSize()-1)/searchParam.getPageSize());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return searchResponseVo;
    }

    //构建搜索请求对象
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        //条件对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //当多个条件的时候  组合条件对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //关键词
        String keyword = searchParam.getKeyword();
        if (!StringUtils.isEmpty(keyword)){
            boolQueryBuilder.filter(QueryBuilders.matchQuery("title",keyword)
            .operator(Operator.AND));
        }else {
            boolQueryBuilder.filter(QueryBuilders.matchAllQuery());
        }

        //品牌  过滤条件   品牌ID:品牌名称
        String trademark = searchParam.getTrademark();
        if (!StringUtils.isEmpty(trademark)){
            String [] t = StringUtils.split(trademark,":");
            boolQueryBuilder.filter(QueryBuilders.termQuery("tmId",t[0]));
        }

        //一二三级分类
        Long category1Id = searchParam.getCategory1Id();
        if (category1Id != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category1Id",category1Id));
        }
        Long category2Id = searchParam.getCategory2Id();
        if (category2Id != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category2Id",category2Id));
        }
        Long category3Id = searchParam.getCategory3Id();
        if (category3Id != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category3Id",category3Id));
        }

        //4:  平台属性ID:平台属性值:平台属性名称
        String[] props = searchParam.getProps();
        if (props != null && props.length > 0){
            //父
            BoolQueryBuilder boolQueryBuilderSon = QueryBuilders.boolQuery();
            for (String prop : props) {
                //平台属性ID:平台属性值:平台属性名称
                String[] split = prop.split(":");
                //子
                BoolQueryBuilder subBoolQuery = QueryBuilders.boolQuery();
                subBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",split[0]));
                subBoolQuery.must(QueryBuilders.termQuery("attrs.attrValue",split[1]));
                boolQueryBuilderSon.must(QueryBuilders.nestedQuery("attrs",subBoolQuery, ScoreMode.None));
            }
            boolQueryBuilder.filter(boolQueryBuilderSon);
        }

        //构建条件对象
        searchSourceBuilder.query(boolQueryBuilder);

        //排序  1:asc  1:desc
        String order = searchParam.getOrder();
        if (!StringUtils.isEmpty(order)){
            String[] o = order.split(":");
            String filed = null;
            switch (o[0]){
                case "1":filed = "hotScore";break;
                case "2":filed = "paice";break;
            }
            searchSourceBuilder.sort(filed,o[1].equalsIgnoreCase(SortOrder.ASC.toString())?SortOrder.ASC:SortOrder.DESC);
        }

        //分页
        Integer pageNo = searchParam.getPageNo();
        Integer pageSize = searchParam.getPageSize();
        searchSourceBuilder.from((pageNo-1)*pageSize);
        searchSourceBuilder.size(pageSize);

        // 高亮    手机是红色
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        //品牌聚合  简单
        searchSourceBuilder.aggregation(AggregationBuilders.terms("aggTmId").field("tmId")
                            .subAggregation(AggregationBuilders.terms("aggTmName").field("tmName"))
                            .subAggregation(AggregationBuilders.terms("aggTmLogoUrl").field("tmLogoUrl")));

        //聚合
        searchSourceBuilder.aggregation(AggregationBuilders.nested("aggAttrs","attrs")
                            .subAggregation(AggregationBuilders.terms("aggAttrId").field("attrs.attrId")
                            .subAggregation(AggregationBuilders.terms("aggAttrName").field("attrs.attrName"))
                            .subAggregation(AggregationBuilders.terms("aggAttrValue").field("attrs.attrValue"))));

        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("goods");
        searchRequest.source(searchSourceBuilder);
        System.out.println(searchRequest);
        return searchRequest;
    }

    //解析结果
    private SearchResponseVo parseSearchResponse(SearchResponse searchResponse) {
        SearchResponseVo searchResponseVo = new SearchResponseVo();

        SearchHits hits = searchResponse.getHits();

        //解析品牌集合
        Map<String, Aggregation> stringAggregationMap = searchResponse.getAggregations().asMap();
        ParsedLongTerms aggTmId = (ParsedLongTerms) stringAggregationMap.get("aggTmId");

        List<SearchResponseTmVo> trademarkList  = aggTmId.getBuckets().stream().map(bucket -> {
            SearchResponseTmVo sVo = new SearchResponseTmVo();
            sVo.setTmId(Long.parseLong(bucket.getKeyAsString()));
            ParsedStringTerms aggTmName = bucket.getAggregations().get("aggTmName");
            ParsedStringTerms aggTmLogoUrl = bucket.getAggregations().get("aggTmLogoUrl");
            sVo.setTmName(aggTmName.getBuckets().get(0).getKeyAsString());
            sVo.setTmLogoUrl(aggTmLogoUrl.getBuckets().get(0).getKeyAsString());
            return sVo;
        }).collect(Collectors.toList());

        ParsedNested aggAttrs = (ParsedNested) stringAggregationMap.get("aggAttrs");

        ParsedLongTerms aggAttrId = aggAttrs.getAggregations().get("aggAttrId");
        List<SearchResponseAttrVo> searchResponseAttrVoList = aggAttrId.getBuckets().stream().map(bucket -> {
            SearchResponseAttrVo searchResponseAttrVo = new SearchResponseAttrVo();
            searchResponseAttrVo.setAttrId(Long.parseLong(bucket.getKeyAsString()));
            ParsedStringTerms aggAttrName = bucket.getAggregations().get("aggAttrName");
            searchResponseAttrVo.setAttrName(aggAttrName.getBuckets().get(0).getKeyAsString());
            ParsedStringTerms aggAttrValue = bucket.getAggregations().get("aggAttrValue");
            List<String> attrValueList = aggAttrValue.getBuckets().stream().map(Terms.Bucket::getKeyAsString).collect(Collectors.toList());
            searchResponseAttrVo.setAttrValueList(attrValueList);
            return searchResponseAttrVo;
        }).collect(Collectors.toList());
        searchResponseVo.setAttrsList(searchResponseAttrVoList);
        searchResponseVo.setTrademarkList(trademarkList);

        //商品结果集
        SearchHit[] hits1 = hits.getHits();

        List<Goods> collect = Arrays.stream(hits1).map(hit -> {
            String sourceAsString = hit.getSourceAsString();
            Goods goods = JSONObject.parseObject(sourceAsString, Goods.class);
            //高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields != null && highlightFields.size() > 0) {
                HighlightField title = highlightFields.get("title");
                if (title != null) {
                    String s = title.fragments()[0].toString();
                    goods.setTitle(s);
                }
            }
            return goods;
        }).collect(Collectors.toList());

        searchResponseVo.setGoodsList(collect);

        searchResponseVo.setTotal(hits.getTotalHits());
        return searchResponseVo;
    }
}
